package club.hicode.daydayup.threadpool;

/**
 * xx
 *
 * @author Liu Chunfu
 * @date 2018-06-21 上午10:28
 **/
public class ThreadSafeSample {
    public int sharedState;

    public void nonSafeAction() {
        while (sharedState < 100000) {
            //i++ 是不会将值重新赋值过去的
            int former = sharedState++;
            int latter = sharedState;

            //System.err.println("former:" + former + " latter:" + latter);

            if (former != (latter - 1)) {
                System.out.printf("Observed data race, former is " + former +
                        ", " + "latter is " + latter);
                return;
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadSafeSample sample = new ThreadSafeSample();
        Thread threadA = new Thread() {
            public void run() {
                sample.nonSafeAction();
            }
        };

        Thread threadB = new Thread() {
            public void run() {
                sample.nonSafeAction();
            }
        };

        threadA.start();
        threadB.start();
        threadA.join();
        threadB.join();
    }
}